eval 'exec perl -wS $0 ${1+"$@"}'
 if 0;

use strict;
use warnings;
use POSIX qw(strftime);

use DBI();
use File::Basename;
use File::stat;
use Data::Dumper 'Dumper';

use IO::Socket;

# Following variable is used as a general file descriptor for all the 
# output of the current tool (the log file). Actually, this file will
# contain the copy of both the stdout and stderr channel.
my $G_LOG;

################################################################################
#
################################################################################
sub get_time
{
    my $separator=shift @_;
    my @timelist = @_;
    
    my $now_time="";
    
    if (! defined $separator)
    {
	$separator=":";
    }
    
    if (scalar @timelist<1)
    {
	@timelist=localtime();
    }
    
    $now_time = strftime("%H".$separator."%M".$separator."%S",@timelist);
    
    return $now_time;
}

################################################################################
#
################################################################################
sub get_date
{
    my $separator=shift @_;
    my @timelist = @_;
    
    my $now_date="";
    
    if (! defined $separator)
    {
	$separator="/";
    }
    
    if (scalar @timelist<1)
    {
	@timelist=localtime();
    }
    
    $now_date = POSIX::strftime("%Y".$separator."%m".$separator."%d",@timelist);
    
    return $now_date;
}

################################################################################
#
################################################################################
sub mylog
{
    if ($G_LOG)
    {
	print $G_LOG get_date()." ".get_time()." ".join("",@_);
    }
}

################################################################################
#
################################################################################
sub error
{
    print STDERR get_date()." ".get_time()." [ERROR] ",@_;
    mylog "[ERROR] ", @_;
}

################################################################################
#
################################################################################
sub warning
{
    print STDERR get_date()." ".get_time()." [WARNING] ",@_;
    mylog("[WARNING],",@_);
}

################################################################################
#
################################################################################
sub debug
{
    my $h_ref_param=shift @_;
    
    if (exists $h_ref_param->{DEBUG})
    {
	print STDOUT get_date()." ".get_time()." [DEBUG] ",@_;
	mylog("[DEBUG] ",@_);
    }
}

################################################################################
#
################################################################################
sub info
{
    print STDOUT get_date()." ".get_time()." [INFO] ",@_;
    mylog("[INFO] ",@_);
}

################################################################################
#
################################################################################
sub print_h_content
{
    my $h_ref_param=shift @_;
    
    debug $h_ref_param, "Printing Global Hash Content:\n";
    debug $h_ref_param, "######################################################\n";
    foreach my $thekey (keys %$h_ref_param)
    {
	debug $h_ref_param, $thekey." => ".$h_ref_param->{$thekey}."\n";
    }
    debug $h_ref_param, "######################################################\n";
}

################################################################################
#
################################################################################
sub db_connect
{
    my $h_ref_param=shift @_;

    my $dbh = DBI->connect("DBI:mysql:database=".$h_ref_param->{DBNAME}.";host=localhost",
                         $h_ref_param->{DBLOGIN}, $h_ref_param->{DBPASSWD},
                         #{'RaiseError' => 0});
			   {'RaiseError' => 0, 'AutoCommit' => 0});

    $h_ref_param->{DB}=$dbh;

    return (defined $dbh);
}

################################################################################
#
################################################################################
sub slsecd_connect
{
    my $h_ref_param=shift @_;
    my $socket=shift @_;
    my $proto=shift @_;
    my $peeraddr=shift @_;
    my $peerport=shift @_;

    $$socket = IO::Socket::INET->new( Proto     => $$proto,
				     PeerAddr  => $$peeraddr,
				     PeerPort  => $$peerport,
				     );
    unless ($$socket)
    {
	return 0;
    }
    return 1;
}

################################################################################
#
################################################################################
sub slsecd_disconnect
{
    my $h_ref_param=shift @_;
    my $socket=shift @_;

    close $$socket;
}

################################################################################
#
################################################################################
sub db_disconnect
{
    my $h_ref_param=shift @_;
    $h_ref_param->{DB}->disconnect();
}

################################################################################
#
################################################################################
sub get_event_id
{
    my $h_ref_param=shift @_;
    my $lref_imei = shift @_;
    my $ref_event_id = shift @_;
    my @data = ();
    my @l1 = ();
    my @l2 = ();
    my @l3 = ();
    my $c = 0;
    my $c1 = 0;
    my $c2 = 0;
    my $sth = "";
    my $element1 = "";
    my $element2 = "";
    my $element3 = "";
    my $sql="";
    
    foreach my $element (@$lref_imei)
    {
	@l1 = ();
	$c++;
	#print $c. "\n";
	#print $element. "\n";
	$sql="SELECT event_id FROM imei WHERE imei = $element and data = '0';";
	#print $sql."\n";
	#$sth = $h_ref_param->{DB}->prepare("SELECT event_id FROM imei WHERE imei = $element and (data = '' or data is null);");
	$sth = $h_ref_param->{DB}->prepare("$sql");
	$sth->execute();
    
	while ( @data = $sth->fetchrow_array ) 
	{
	    #print "imei: " .$element. " event_id: " .$data[0]. "\n";
	    push (@l1,$data[0]);
	}
	
	if ($c == 1)
	{
	    @l2 = @l1;
	    next;
	}

	@l3 = ();

	foreach $element2 (@l2)
	{
	    #print $element2. "\n";
	    foreach $element1 (@l1)
	    {
		if ($element2 == $element1)
		{
		    push (@l3,$element2);
		    debug $h_ref_param, "Common ID :" .$element2. "\n";
		}
	    }

	    foreach $element3 (@l3)
	    {
		$c1++
	    }
	}
	
	@l2 = ();
	@l2 = @l3;
	
    }
    
    foreach $element3 (@l3)
    {
	#print "Result :" .$element3. "\n";
	$c2++;
	$$ref_event_id = $element3;
    } 

    if ($c2 > 1)
    {
	return 0;
    }
    
    return 1;
}

################################################################################
#
################################################################################
sub get_enciphered_data
{
    my $h_ref_param=shift @_;
    my $lref_data = shift @_;
    my $lref_secdata = shift @_;
    my $data = "";
    my $result = "";
    my $socket=0;
    my $proto="tcp";
    #my $peeraddr="172.24.61.137";
    my $peeraddr="127.0.0.1";
    my $peerport="30000";

    @$lref_secdata = ();

    #warn Dumper [@$socket];

    if (! slsecd_connect($h_ref_param,\$socket,\$proto,\$peeraddr,\$peerport))
    {
	error("Failed to connect to slsecd.\n");
	return 4;
    }

    foreach my $data (@$lref_data)
    {
	$data =~s/ //g;
	#$data="352315012021636;0421345817;;;;;;";
	#print $data. "\n";
	print $socket "E;" .$data. "\n";
	$result = <$socket>;
	
	$result=~s/\r\n$//;
	$result=~s/\n\r$//;
	$result=~s/\n$//;
	$result=~s/\r$//;
	
	chomp($result);

	#debug $h_ref_param, "Executing in 'get_enciphered_data' function:>$result<\n";

	#$result = chomp ($result);
	debug $h_ref_param, "Result: >$result<\n";
	#print $result ."\n";
	push (@$lref_secdata,$result);
	#print $data. "\n";
    }

    print $socket "Q\n";
    if (! slsecd_disconnect($h_ref_param,\$socket))
    {
	warning("Failed to disconnect from slsecd.\n");
    }

    return 1;
}

################################################################################
#
################################################################################
sub db_data_update
{
    my $h_ref_param=shift @_;
    my $lref_secdata = shift @_;
    my $event_id = shift @_;
    my $sth;
    my @lsec_data;
    
    # trap errors using eval{}
    eval {
	foreach my $element (@$lref_secdata)
	{
	    @lsec_data = split(/;/, $element);
	    
	    #$sth = $h_ref_param->{DB}->prepare("update imei set opl_id = '$opl_id',data = '$lsec_data[1]' where imei = '$lsec_data[0]';");
	    $sth = $h_ref_param->{DB}->prepare("update imei set data = '$lsec_data[1]' where imei = '$lsec_data[0]' and event_id = '$event_id';");
	    #print $sth. "\n";
	    #debug $h_ref_param, $sth. "\n";
	    $sth->execute();
	    $h_ref_param->{DB}->commit();
	}
    };
    
    if ( $@ )
    {
	error("Transaction aborted: $@\n");
	$h_ref_param->{DB}->rollback();
	return 0;
    }
    
    return 1;

}

################################################################################
#
################################################################################
sub zero_key
{
    my $key= shift @_;

    if ($key == "0000000000")
    {
	$key="";
    }
    else
    {
	$key=$key;
    }

    return $key;
    
}

################################################################################
#
################################################################################
sub get_file_content
{
    my $h_ref_param=shift @_;
    my $file = shift @_;
    my $lref_data = shift @_;
    my $lref_imei = shift @_;
    my $line = "";
    my $file_format = 0;
    my @file_content = ();

    @$lref_data = ();
    @$lref_imei = ();

    open(FILE, "<$file");
    @file_content = <FILE>;

    #foreach $line (@file_content)
    #{
	if ($line =~/^     IMEI=     ;      N=  ; UNLOCK N=;    NS=   ;UNLOCK NS=;   SP=    ;UNLOCK SP=;    C=    ;UNLOCK C= ;    SIM = ;UNLOCK S=/)
	{
	    $file_format = 1;
	}
	
	if ($line =~/^     IMEI=     ;      N=  ;UNLOCK N= ;/)
	{
	    $file_format = 2; 
	}

	if ($line =~/HDRSUPSTXUC.+/)
	{
	    $file_format = 3; 
	}
	if ($line =~/IMEI            NCK/)
	{
	    $file_format = 4; 
	}
	if ($line =~/^DATE OF DELIVERY/)
	{
	    $file_format = 5; 
	}
	if ($line =~/^LISTING FOR.+/)
	{
	    $file_format = 6; 
	}
	if ($line =~/^\d{18}SFREQUIP\d{16}/)
	{
	    $file_format = 7; 
	}
	if ($line =~/^ALC.{63}(\d{15}).{6}(\d{10}).+/)
	{
	    $file_format = 8; 
	}
	if ($line =~/^(\d{15});(\d{10});(\d{10});(\d{10}) ;(\d{2})\/(\d{2})\/(\d{2})$/)
	{
	    $file_format = 9; 
	}
	#if ($line =~/^(\d{15}),(\d{10}),.$/)
        if($file_content[0] =~/^(\d{15}),(\d{10}),.$/)
	{
	    $file_format = 10; 
	}
    
    if($file_content[0] =~/^TMN ORDER NUMBER:.+/)
    {
	$file_format = 11;
    }

    if($file_content[0] =~/^LISTING.{1}FOR.+/)
    {
	$file_format = 12;
    }

    if($file_content[0] =~/^DATE.{1}OF.{1}DELIVERY.+/)
    {
	$file_format = 13;
    }
    
    #}
    
    #print "File: " .$file. "/ Format: " . $file_format. "\n";
    if ($file_format == 0)
    {
	return 0;
    }

    if ($file_format == 1)
    {
	foreach $line (@file_content)
	{
	    if ($line =~/^(\d{15});(\d{10});([0-9 ]{10});([0-9 ]{10});([0-9 ]{10});([0-9 ]{10});([0-9 ]{10});([0-9 ]{10});([0-9 ]{10});([0-9 ]{10});([0-9 ]{10})/)
	    {
		push(@$lref_data,$1. ";" .$2. ";" .$4. ";" .$6. ";" .$8. ";" .$10. ";;"); 
		push(@$lref_imei,$1); 
	    }
	} # foreach $line (@file_content)
    } # if ($file_format == 1)
    
    elsif  ($file_format == 2)
    {	
	foreach $line (@file_content)
	{
	    if ($line =~/^(\d{15});(\d{10});([0-9 ]{10});/)
	    {
		push(@$lref_data,$1. ";" .$2. ";;;;;;");
		push(@$lref_imei,$1); 
	    }
	} # foreach $line (@file_content)
    } # elsif ($file_format == 2)
    
    elsif ($file_format == 3)
    {	
	foreach $line (@file_content)
	{
	    #if ($line =~/^SETPODIRECTALC-STD-E[0-9]{3}[ ]{3}(\d{15})[ ]{7}(\d{10})[ ]{6}([0-9 ]{10})/)
	    if ($line =~/^.{23}[ ]{3}(\d{15})[ ]{7}(\d{10})[ ]{6}([0-9 ]{10})/)
	    {
		#print $line. "\n";
		push(@$lref_data,$1. ";" .$2. ";;" .$3. ";;;;");
		push(@$lref_imei,$1); 
	    }
	} # foreach $line (@file_content)
    } # elsif ($file_format == 3)

    elsif  ($file_format == 4)
    {	
	foreach $line (@file_content)
	{
	    if ($line =~/^(\d{15});(\d{10});/)
	    {
		push(@$lref_data,$1. ";" .$2. ";;;;;;");
		push(@$lref_imei,$1); 
	    }
	} # foreach $line (@file_content)
    } # elsif ($file_format == 4)

    elsif  ($file_format == 5)
    {	
	foreach $line (@file_content)
	{
	    if ($line=~/^.+(\d{15}).+(\d{10}).+(\d{10}).+(\d{10}).+(\d{10}).+(\d{10}).+(\d{10})/)
	    #if ($line =~/^IMEI=(\d{15}S(\d{10})/)
	    {
		push(@$lref_data,$1.";".zero_key($2).";".zero_key($3).";".zero_key($4).";".zero_key($5).";".zero_key($6).";".zero_key($7).";");
		push(@$lref_imei,$1); 
	    }
	} # foreach $line (@file_content)
    } # elsif ($file_format == 5)

    elsif  ($file_format == 6)
    {	
	foreach $line (@file_content)
	{
	    if ($line=~/^.+(\d{15}).+(\d{10}).+(\d{10}).+(\d{10}).+(\d{10}).+(\d{10})/)
	    {

		push(@$lref_data,$1.";".zero_key($2).";".zero_key($3).";".zero_key($4).";".zero_key($5).";;".zero_key($6).";");
		push(@$lref_imei,$1); 
	    }
	} # foreach $line (@file_content)

    } # elsif ($file_format == 6)

    elsif  ($file_format == 7)
    {	
	foreach $line (@file_content)
	{
	    if ($line=~/^(.{1})(\d{15})(.{7})(\d{10})/)
	    {
		push(@$lref_data,$2. ";" .$4. ";;;;;;");
		push(@$lref_imei,$2); 
	    }
	} # foreach $line (@file_content)
    } # elsif ($file_format == 7)

    elsif  ($file_format == 8)
    {	
	foreach $line (@file_content)
	{
	    if ($line=~/^ALC.{63}(\d{15}).{6}(\d{10}).+/)
	    {
		push(@$lref_data,$1. ";" .$2. ";;;;;;");
		push(@$lref_imei,$1); 
	    }
	} # foreach $line (@file_content)
    } # elsif ($file_format == 8)

    elsif  ($file_format == 9)
    {	
	foreach $line (@file_content)
	{
	    if ($line=~/^(\d{15});(\d{10});(\d{10});(\d{10}) ;(\d{2})\/(\d{2})\/(\d{2})$/)
	    {
		push(@$lref_data,$1. ";" .$2. ";;;;;;");
		push(@$lref_imei,$1); 
	    }
	} # foreach $line (@file_content)
    } # elsif ($file_format == 9)
    
    elsif  ($file_format == 10)
    {	
	foreach $line (@file_content)
	{
	    if ($line =~/^(\d{15}),(\d{10}),.$/)
	    {
		push(@$lref_data,$1. ";" .$2. ";;;;;;");
		push(@$lref_imei,$1); 
	    }
	} # foreach $line (@file_content)
    } # elsif ($file_format == 10)

    elsif  ($file_format == 11)
    {
	foreach $line (@file_content)
	{
	    if ($line =~/^(\d{15})(.{10})(\d{10})/)
	    {
		push(@$lref_data,$1. ";" .$3. ";;;;;;");
		push(@$lref_imei,$1);
	    }
	} # foreach $line (@file_content)
    } # elsif ($file_format == 11)
    
    elsif  ($file_format == 12)
    {
	foreach $line (@file_content)
	{
	    if ($line =~/^IMEI=(\d{15})\sN=(.{10})\sNS=(\d{10})\sSP=(\d{10})\sS=(\d{10})\sC=(\d{10})\sRC=(\d{10})/)
	    {
		push(@$lref_data,$1.";".zero_key($2).";".zero_key($3).";".zero_key($4).";".zero_key($5).";".zero_key($6).";".zero_key($7).";");
		push(@$lref_imei,$1);
	    }
	    if ($line =~/^IMEI=(\d{15})\sN=(.{10})\sNS=(\d{10})\sSP=(\d{10})\sC=(\d{10})\sRC=(\d{10})/)
	    {
		push(@$lref_data,$1.";".zero_key($2).";".zero_key($3).";".zero_key($4).";;".zero_key($5).";".zero_key($6).";");
		push(@$lref_imei,$1);
	    }
	} # foreach $line (@file_content)
    } # elsif ($file_format == 12)

    elsif  ($file_format == 13)
    {
	foreach $line (@file_content)
	{
	    if ($line =~/^IMEI=(\d{15})\sN=(.{10})\sNS=(\d{10})\sSP=(\d{10})\sS=(\d{10})\sC=(\d{10})\sRC=(\d{10})/)
	    {
		push(@$lref_data,$1.";".zero_key($2).";".zero_key($3).";".zero_key($4).";".zero_key($5).";".zero_key($6).";".zero_key($7).";");
		push(@$lref_imei,$1);
	    }
	    if ($line =~/^IMEI=(\d{15})\sN=(.{10})\sNS=(\d{10})\sSP=(\d{10})\sC=(\d{10})\sRC=(\d{10})/)
	    {
		push(@$lref_data,$1.";".zero_key($2).";".zero_key($3).";".zero_key($4).";;".zero_key($5).";".zero_key($6).";");
		push(@$lref_imei,$1);
	    }
	} # foreach $line (@file_content)
    } # elsif ($file_format == 13)
        
    else
    {
	# file format unknown
	return 0;
    }

    if (scalar @$lref_imei == 0)
    {
	return 0;
    }
    
    #warn Dumper [@$lref_data];
    return 1;
}

################################################################################
#
################################################################################
sub file_already_processed

{
    my $h_ref_param = shift @_;
    my $lref_imei = shift @_;
    my $c1 = 0;
    my $c2 = 0;
    my $c3=0;
    my $res=0;
    my $sql="";

    foreach my $imei (@$lref_imei)
    {
	$sql="SELECT COUNT(*) FROM imei where imei='$imei';";
	#print $sql."\n";
	$c1++;
	my $sth = $h_ref_param->{DB}->prepare("$sql");
	$sth->execute();
	my $ref = $sth->fetchrow_hashref();
	
	$sth->finish();
	
	if ($ref->{'COUNT(*)'} > 0)
	{
	    # imei exists in db
	    $c2++;

	    #$sql="SELECT COUNT(*) FROM imei where imei='$imei' and data IS NOT NULL;";
	    $sql="SELECT COUNT(*) FROM imei where imei='$imei' and data != '0';";
	    #print $sql."\n";
	    $sth = $h_ref_param->{DB}->prepare("$sql");
	    $sth->execute();
	    $ref = $sth->fetchrow_hashref();
	    #print $imei." ".$ref->{'COUNT(*)'}."\n";
	    
	    $sth->finish();
	    if ($ref->{'COUNT(*)'} > 0)
	    {
		# imei exists in db with data
		$c3++;
	    }
	}
    }

    print "c1: ".$c1."\n";
    print "c2: ".$c2."\n";
    print "c3: ".$c3."\n";

    # file already processed
    if ($c1 == $c3)
    {
	$res=0;
	return $res;
    }

    #mo IMEI found in db
    #if ($c2 == 0)
    if ($c2 == 0 || $c2 != $c1)
    {
	$res=1;
	return $res;
    }

    #imei found in db without data
    $res=2;
    return $res;
}

################################################################################
#
################################################################################
sub db_add_event
{
    my $h_ref_param=shift @_;
    my $res=0;
    my $sth;
    my $insert_date = "";
    $insert_date=get_date("-")." ".get_time(":");
    my $event_id=0;

    # trap errors using eval{}
    eval {
	$h_ref_param->{DB}->do("LOCK TABLES event WRITE") || die "LOCK TABLES failed";
	$sth = $h_ref_param->{DB}->prepare("INSERT INTO event (event_type_id,date,data) VALUES (2,'$insert_date',0);");
	$res=$sth->execute();
    };
    
    if ( $@ )
    {
	error("Transaction aborted: $@\n");
	$h_ref_param->{DB}->rollback();
	return 0;
    }

    #$event_id=$h_ref_param->{DB}->last_insert_id(undef,undef,"event","id");
    $event_id=$h_ref_param->{DB}->{ q{mysql_insertid}};
    #print "event ID: ".$event_id."\n";
    $h_ref_param->{DB}->do("UNLOCK TABLES") || die "UNLOCK TABLES failed";

    return $event_id;
    #return 1;
}

################################################################################
#
################################################################################
sub db_imei_insert
{
    my $h_ref_param=shift @_;
    my $limei = shift @_;
    my $event_id = shift @_;
    my $res=0;
    my $sth;
    my $sql="";

    # trap errors using eval{}
    eval {
	foreach my $imei (@$limei)
	{
	    #    push(@sql;"INSERT INTO imei (imei,event_id,imei_additional_info_id) VALUES ( '$imei','$event_id',0);");
	    #}
	    #print $sql;
	    
	    $sth=$h_ref_param->{DB}->prepare("INSERT INTO imei (imei,event_id,imei_additional_info_id) VALUES ( '$imei','$event_id',0);");
	    #$sth=$h_ref_param->{DB}->prepare(@sql);
	    $res=$sth->execute();
	}
	
    };
    
    if ( $@ )
    {
	error("Transaction aborted: $@\n");
	$h_ref_param->{DB}->rollback();
	return 0;
    }

    #return $res;
    return 1;
}

################################################################################
#
################################################################################
sub process
{
    my $h_ref_param=shift @_;
    my $err=0;
    my @ldata = ();
    my @limei = ();
    my @lsecdata = ();
    my $res=0;
    my $result=0;
    my $event_id=0;
    
    print_h_content($h_ref_param);
    
    if (! db_connect($h_ref_param))
    {
	error("Failed to connect to database.\n");
	#$res=3;
	#goto ENDPROCESS;
	return 3;
    }
    
    #info "Processing file $h_ref_param->{INPUTFILE}... \n";

    chomp($h_ref_param->{INPUTFILE});

    my ($name,$path,$suffix) = fileparse("$h_ref_param->{INPUTFILE}",());
	   
    info "Extracting file content... \n";
    if (! get_file_content($h_ref_param,$h_ref_param->{INPUTFILE},\@ldata,\@limei,))
    {
	error("file format not supported.\n");
	$res=7;
	goto ENDPROCESS;
    }

    #warn Dumper [@ldata];

    info "Checking file... \n";
    # already processed
    #file_already_processed($h_ref_param,\@limei);
    $result=file_already_processed($h_ref_param,\@limei);
    print "result: ".$result."\n";
    if ($result == 0)
    {
	info("File $name already processed. Skipping...\n");
	$res=8;
	goto ENDPROCESS;
    }
    elsif ($result == 1)
    {
	warning("No IMEI found in db. Adding new event...\n");
	$event_id=db_add_event($h_ref_param);
	#print "event ID: ".$event_id."\n";
	if ($event_id == 0)
	{
	    error("Couldn't insert event from file $name into DB. \n");
	    $res=14;
	    goto ENDPROCESS;
	}
	info("Inserting IMEI list into DB... \n");
	#warn Dumper [@limei];
	if (! db_imei_insert($h_ref_param,\@limei,$event_id))
	{
	    error("Couldn't insert imei list from file $name into DB. \n");
	    $res=15;
	    goto ENDPROCESS;
	}
	goto ENCDATA;
    }
    else
    {
	debug $h_ref_param, "Get event_id for file: $name \n";
	info "Getting EVENT_ID from database...\n";
	if (! get_event_id($h_ref_param,\@limei,\$event_id))
	{
	    error("Couldn't get event_id from file $name. \n");
	    $res=9;
	    goto ENDPROCESS;
	}
	
	#$event_id = "";
	#print "event_id: " .$event_id. "\n";
	
	if (($event_id eq 0) || ($event_id eq ""))
	{
	    error("EVENT_ID not expected value. \n");
	    $res=10;
	    goto ENDPROCESS;
	}
	debug $h_ref_param, "Common event_id :" .$event_id. "\n";

	ENCDATA:;

	info "Enciphering data...\n";
	if (! get_enciphered_data($h_ref_param,\@ldata,\@lsecdata))
	{
	    error("Couldn't encipher data from file $name. \n");
	    $res=11;
	    goto ENDPROCESS;
	}
	
	info "Updating secure data into database...\n";
	if (! db_data_update($h_ref_param,\@lsecdata,$event_id))
	{
	    error("Couldn't update secure data from file $name to DB. \n");
	    $res=12;
	    goto ENDPROCESS;
	}
    }
    
  ENDPROCESS:;
    
    #info "End of Process. \n";
    
    if (! db_disconnect($h_ref_param))
    {
	warning "Failed to disconnect from database.\n";
    }
    
    return $res;
}

################################################################################
#
################################################################################
sub print_version
{
  my $h_ref_param=shift @_;
  print $h_ref_param->{EXECUTABLE_NAME}." ".$h_ref_param->{VERSION}." ".$h_ref_param->{RELEASE_DATE}."\n";
}

################################################################################
#
################################################################################
sub parse_args
{
    my $h_ref_param=shift @_;
    
    my $arg="";
    my $err=0;
    
    while ($arg=shift @ARGV)
    {
	chomp($arg);
	if ( $arg =~ /^-/ )
	{
	    if ( ($arg =~ /^-h/) || ($arg =~ /^--help/))
	    {
		print_usage($h_ref_param);
		exit(0);
	    }
	    elsif ( ($arg =~ /^-d/) || ($arg =~ /^--debug/))
	    {
		$h_ref_param->{DEBUG}=1;
	    }
	    elsif ( ($arg =~ /^-v/) || ($arg =~ /^--version/))
	    {
		print_version();
		exit(0);
	    }
	    
	    elsif ( ($arg =~ /^-l/) || ($arg =~ /^--log/))
	    {
		$arg=shift @ARGV;
		$h_ref_param->{LOG}=$arg;
	    }

	    else
	    {
		error "Unexpected option >$arg<.\n";
		$err++;
		next;
	    } 
	}
	else
	{
	    
	    #<inputfile>: Mandatory. Input File\n";
	    if (! exists $h_ref_param->{INPUTFILE})
	    {
		$h_ref_param->{INPUTFILE}=$arg;
	    }
	    #<dbname>: Mandatory. Local database name to use <dbname> database.\n";
	    elsif (! exists $h_ref_param->{DBNAME})
	    {
		$h_ref_param->{DBNAME}=$arg;
	    }
	    #<dblogin>: Mandatory. Local database login to use <dbname> database.\n";
	    elsif (! exists $h_ref_param->{DBLOGIN})
	    {
		$h_ref_param->{DBLOGIN}=$arg;
	    }
	    #<dbpasswd>: Mandatory. Local database password to use <dbname> database.\n";
	    elsif (! exists $h_ref_param->{DBPASSWD})
	    {
		$h_ref_param->{DBPASSWD}=$arg;
	    }
	}
    }
    
    if (! exists $h_ref_param->{DBPASSWD})
    {
	error("Missing arguments.\n");
	$err++;
    }
    
    if ($err>0)
    {
	error "Aborting due to previous error(s). Use -h or --help for usage.\n";
	return 1;
    }
    
    return 0;
}
    
################################################################################
#
################################################################################
sub print_usage
  {
    my $h_ref_param=shift @_;

    print "USAGE: ".$h_ref_param->{EXECUTABLE_NAME}." [-h|--help] [-d|--debug] [-v|--version] [-l|--log <log file>] ...] <inputfile> <dbname> <dblogin> <dbpasswd>\n";
    print "\n";
    print "PURPOSE:\n";
    print "   Insert ciphered data into the database \n";
    print "\n";
    print "PARAMETERS DESCRIPTION:\n";
    print "\n";
    print "   <inputfile>: Mandatory. input file.\n";
    print "\n";
    print "   <dbname>: Mandatory. Local database name to use <dbname> database.\n";
    print "\n";
    print "   <dblogin>: Mandatory. Local database login to use <dbname> database.\n";
    print "\n";
    print "   <dbpasswd>: Mandatory. Local database password to use <dbname> database.\n";
    print "\n";
    print "OPTIONS DESCRIPTION:\n";
    print "   [-h|--help]:\n";
    print "      Print this usage message and exit.\n";
    print "\n";
    print "   [-v|--version]:\n";
    print "      Print the version number and exit.\n";
    print "\n";
    print "   [-d|--debug]:\n";
    print "      Print excessive output to understand the processing.\n";
    print "\n";
    print "\n";
  }

################################################################################
#
################################################################################
sub open_log
{
    my $h_ref_param=shift @_;

    if (! open($G_LOG,">>".$h_ref_param->{LOG}))
    {
	warning "Cannot create log file ".$h_ref_param->{LOG}." in current directory.\n";

	$h_ref_param->{LOG}="/tmp/".$h_ref_param->{EXECUTABLE_NAME}.".log";

	if (! open($G_LOG,">".$h_ref_param->{LOG}))
	{
	    warning "Still cannot create alternative log file ".$h_ref_param->{LOG}.". No log will be performed.\n";
	    $G_LOG=0;
	}
    }
}

################################################################################
#
################################################################################
sub intro
  {
    my $h_ref_param=shift @_;
    my $err=0;
    my $date_for_file="";

    # Updating some global variables.

    $h_ref_param->{START_TIME}=get_date("-")." ".get_time(":");

    $date_for_file=get_date("-")."_".get_time("-");
    
    $h_ref_param->{VERSION}="0.9.14";
    $h_ref_param->{EXECUTABLE_NAME}="import_keys.pl";

    $h_ref_param->{LOG}=$h_ref_param->{EXECUTABLE_NAME}.".$date_for_file.log";

    $h_ref_param->{LOCK_FILE}="/tmp/".$h_ref_param->{EXECUTABLE_NAME}.".lock";
    
    $h_ref_param->{RELEASE_DATE}="2007/10/26";

    # Following instruction forces flushing for each output to STDOUT or STDERR.
    $|=1;

    return 0;
  }

################################################################################
#
################################################################################
sub outtro
{
    my $h_ref_param=shift @_;
    if ($G_LOG)
    {
	close($G_LOG);
    }

    return 0;
}

################################################################################
#
################################################################################
sub main
{
  # This hash list will be used to store input parameters and some other
  # usefull information.
  # The actual valable keys are:
  #   VERSION:           string: current version of the tool.
  #   START_TIME:        string: start time of the script in the form YY_MM_DD.HH.MM.SS
  #   EXECUTABLE_NAME:   string: name of the current script.
  #   LOG:               string: name of the log file.
  #   RELEASE_DATE:      string: date of current tool release in form: YYYY/MM/DD
  #   DEBUG:             boolean: if this key exists, then the current script is run in
  #                               debug mode.
  #
  my %params=();
  my $res;
  
  if (intro(\%params)!=0)
  {
      error "Error while executing intro... Aborting.\n";
      exit(1);
  }

  if (parse_args(\%params)!=0)
  {
      error "Error while parsing arguments... Aborting.\n";
      exit(2);
  }
  
  open_log(\%params);
  
  $res = process(\%params);
  #if ($res!=0)
  #{
      #error "Error while processing... Aborting.\n";
  #}

  if (outtro(\%params)!=0)
  {
      error "Error while executing outtro... Aborting.\n";
      exit(13);
  }

  exit($res);

}

################################################################################
#
################################################################################

main();
exit(0);

